<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 将 x 减到 0 的最小操作次数 -->
    <script>
      function fn(nums, x) {
        let sum = nums.reduce((sum, item) => sum + item, 0)
        if (sum < x) {
          // 和小于x，直接return -1
          return -1
        }
        let left = -1
        let right = 0
        let ans = Infinity
        for (left; left < nums.length; left++) {
          if (left !== -1) {
            sum += nums[left] // sum增大
          }
          if (sum < x) {
            // sum过小，需右移left，使其增大
            continue
          }
          // sum过大，需右移right，使其减小，直至越界或不大于x
          while (right < nums.length && sum > x) {
            sum -= nums[right]
            right++
          }
          // 满足条件
          if (sum === x) {
            ans = Math.min(ans, left + 1 + nums.length - right)
          }
        }
        return isFinite(ans) ? ans : -1
      }
      console.log(fn([1, 1, 4, 2, 3], 5))
    </script>
  </body>
</html>
